<template>
  <div class="player" v-show="this.sequenceList.length">
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div ref="normal" class="normal-player" :class="zindex" v-show="this.fullScreen">
        <div class="background">
          <img width="100%" height="100%" :src="playingSong.img">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title">{{playingSong.name}}</h1>
          <h2 class="subtitle">{{playingSong.singer}}</h2>
        </div>
        <div
          class="middle"
          @touchstart.prevent="middleTouchStart"
          @touchmove.prevent="middleTouchMove"
          @touchend.prevent="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper">
              <div class="cd" :class="cdClass" ref="cdwrapper">
                <img class="image" :src="playingSong.img">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLyric&&currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p
                  ref="lyricLine"
                  class="text"
                  :class="{'current':lyricIndex===index}"
                  v-for="(item,index) in currentLyric.lines"
                  :key="index"
                >{{item.txt}}</p>
              </div>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active':currentShow=='cd'}"></span>
            <span class="dot" :class="{'active':currentShow=='lyric'}"></span>
          </div>
          <!-- 播放器进度条 -->
          <div class="progress-wrapper">
            <span class="time time-l">{{formate(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <bar @touchMove="touchMove" :precent="precent"></bar>
            </div>
            <span class="time time-r">{{formate(playingSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left">
              <i @click="sequence" :class="playmode"></i>
            </div>
            <div class="icon i-left">
              <i @click="prev" class="icon-prev"></i>
            </div>
            <div class="i-center icon">
              <i @click="changePlaying" :class="playIcon"></i>
            </div>
            <div class="icon i-right">
              <i @click="next" class="icon-next"></i>
            </div>
            <div class="icon i-right">
              <i class="icon icon-not-favorite"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" @click="toFullScreen" v-show="!this.fullScreen">
        <div class="icon">
          <img width="40" height="40" :class="cdClass" :src="playingSong.img" alt>
        </div>
        <div class="text">
          <h2 class="name">{{playingSong.name}}</h2>
          <p class="desc">{{playingSong.album}}</p>
        </div>
        <div class="control">
          <!-- stop阻止父元素冒泡 -->
          <i @click.stop="changePlaying" :class="minPlatIcon"></i>
        </div>
        <div class="control">
          <i class="icon-playlist"></i>
        </div>
      </div>
    </transition>
    <audio
      ref="audio"
      :src="playingSong.url"
      @ended="end"
      @timeupdate="timeUpDate"
      @canplay="ready"
      @error="error"
    ></audio>
  </div>
</template>

<script>
import scroll from '../base/scroll'
import { shuffle, copyArr } from '../../common/js/index'
import { mapGetters, mapMutations } from 'vuex'
import animations from 'create-keyframe-animation'
import Bar from '../base/bar'
import Lyric from 'lyric-parser'

export default {
  data() {
    return {
      params: {
        key: 579621905
      },
      songReady: false,
      currentTime: 0,
      precent: 0,
      lyric: '',
      currentLyric: null,
      lyricIndex: 0,
      currentShow: 'cd',
      touch: {},
      playingLyric: ''
    }
  },
  computed: {
    sequenceIndex() {
      return this.sequenceList.findIndex(e => {
        return e.id == this.playingSong.id
      })
    },
    playmode() {
      return this.mode === 0
        ? 'icon-sequence'
        : this.mode === 1
          ? 'icon-random'
          : 'icon-loop'
    },
    zindex() {
      return this.fullScreen ? '' : 'fullScreen'
    },
    cdClass() {
      return this.playing ? 'play' : 'play pause'
    },
    playIcon() {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    minPlatIcon() {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    ...mapGetters([
      'fullScreen',
      'playList',
      'playingSong',
      'playing',
      'currentIndex',
      'sequenceList',
      'mode'
    ]),
    barLength() {
      return window.screen.width
    }
  },
  methods: {
    middleTouchStart(e) {
      this.touch.init = true

      this.touch.startX = e.touches[0].pageX
      this.touch.startY = e.touches[0].pageY
    },
    middleTouchMove(e) {
      if (!this.touch.init) {
        return
      }
      let touch = e.touches[0]
      let deltaX = touch.pageX - this.touch.startX
      let deltaY = touch.pageY - this.touch.startY
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        return
      }
      let left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      const width = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      this.touch.precent = Math.abs(width / window.innerWidth)
      this.$refs.lyricList.$el.style.transform = `translateX(${width}px)`
    },
    middleTouchEnd() {
      let width
      if (this.currentShow === 'cd') {
        if (this.touch.precent > 0.2) {
          width = -window.innerWidth
          this.currentShow = 'lyric'
          this.$refs.middleL.style.opacity = 0
          this.$refs.middleL.style.transition = 'opacity 0.4s'
        } else {
          width = 0
        }
      } else {
        if (this.touch.precent < 0.8) {
          width = 0
          this.currentShow = 'cd'
          this.$refs.middleL.style.opacity = 1
          this.$refs.middleL.style.transition = 'opacity 0.4s'
        } else {
          width = -window.innerWidth
        }
      }
      console.log(width)
      this.$refs.lyricList.$el.style.transform = `translateX(${width}px)`
    },

    end() {
      if (this.mode === 2) {
        this.loop()
      } else {
        this.next()
      }
    },
    loop() {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    back() {
      this.setFullScreen(false)
    },
    toFullScreen() {
      this.setFullScreen(true)
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN',
      setPlaying: 'SET_PLAYING',
      setIndex: 'SET_CURRENT_INDEX',
      setMode: 'SET_MODE',
      setPlayList: 'SET_PLAY_LIST'
    }),
    enter(el, done) {
      const { x, y, scale } = this._getDiatanceAndScale()
      let animation = {
        0: {
          transform: `translate(${-x}px,${y}px) scale(${scale})`
        },
        60: {
          transform: 'translate(0,0) scale(1.1)'
        },
        100: {
          transform: 'translate(0,0) scale(1)'
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400, // 动画时长
          easing: 'linear' // 动画曲线
        }
      })
      // 绑定动画 并执行
      animations.runAnimation(this.$refs.cdwrapper, 'move', done)
    },
    afterEnter(el) {
      animations.unregisterAnimation('move')
      this.$refs.cdwrapper.style.animation = ''
    },
    leave(el, done) {
      const { x, y, scale } = this._getDiatanceAndScale()
      this.$refs.cdwrapper.style.transition = 'all 0.4s'
      this.$refs.cdwrapper.style.transform = `translate(${-x}px,${y}px) scale(${scale})`
      this.$refs.cdwrapper.addEventListener('transitionend', done)
    },
    afterLeave(el) {
      this.$refs.cdwrapper.style.transition = ''
      this.$refs.cdwrapper.style.transform = ''
    },
    sequence() {
      const mode = (this.mode + 1) % 3
      this.setMode(mode)
      let list = []
      if (this.mode === 1) {
        var arr = copyArr(this.sequenceList)
        list = shuffle(arr)
      } else {
        list = this.sequenceList
      }
      this.setIndex(this.getPlayingIndex(list))
      this.setPlayList(list)
    },
    changePlaying() {
      if (!this.songReady) {
        return
      }
      this.setPlaying(!this.playing)
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    getPlayingIndex(list) {
      for (let i = 0; i < list.length; i++) {
        if (list[i] === this.playingSong) {
          return i
        }
      }
    },
    prev() {
      if (!this.songReady) {
        return
      }
      if (this.currentIndex <= 0) {
        this.setIndex(this.playList.length - 1)
        if (!this.playing) {
          this.setPlaying(true)
        }
      } else {
        this.setIndex(this.currentIndex - 1)
        if (!this.playing) {
          this.setPlaying(true)
        }
      }
      this.songReady = false
    },
    next() {
      if (!this.songReady) {
        return
      }
      if (this.currentIndex >= this.playList.length - 1) {
        this.setIndex(0)
        if (!this.playing) {
          this.changePlaying()
        }
      } else {
        this.setIndex(this.currentIndex + 1)
        if (!this.playing) {
          this.changePlaying()
        }
      }
      this.songReady = false
    },
    ready() {
      this.songReady = true
    },
    // 避免网络等错误造成按钮点击不生效的情况
    error() {
      this.songReady = true
    },
    timeUpDate(e) {
      this.currentTime = e.target.currentTime
    },
    formate(timee) {
      let time = Math.trunc(timee)
      let min = Math.trunc(time / 60)
      let second = time % 60
      if (second < 10) {
        second = `0${second}`
      }
      return `${min}:${second}`
    },
    touchMove(percent) {
      let currentTime = percent * this.playingSong.duration
      this.$refs.audio.currentTime = currentTime
      if (!this.playing) {
        this.changePlaying()
      }
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    _getDiatanceAndScale() {
      const paddingbottom = 30
      const paddingleft = 40
      const currentleft = window.screen.width / 2
      const currenttop = currentleft * 0.8 + 85
      const x = currentleft - paddingleft
      const y = window.screen.height - paddingbottom - currenttop
      const scale = (40 / currentleft) * 0.8
      return { x, y, scale }
    },
    getLyric(mid) {
      this.axios
        .get('https://api.bzqll.com/music/tencent/lrc', {
          params: Object.assign(this.params, { id: mid })
        })
        .then(res => {
          if (res.status === 200) {
            this.lyric = res.data
            this.currentLyric = new Lyric(this.lyric, this.handleLyric)
            console.log('haha')
            if (this.playing) {
              this.currentLyric.play()
            }
          }
        })
    },
    handleLyric({ lineNum, txt }) {
      this.lyricIndex = lineNum
      if (lineNum > 5) {
        let lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
      this.playingLyric = txt
    }
  },
  watch: {
    playingSong(newS, oldS) {
      // //playingSong看起来没有改变；
      // 但是playingsong是根据playlist 和currentindex计算得来的
      // 当这两者改变时playingsong相当于改变了 虽然实际上看起来没有变化
      if (this.currentLyric) {
        this.currentLyric.stop()
      }
      if (newS.id == oldS.id) {
        return
      }
      this.$nextTick(() => {
        this.$refs.audio.play()
        this.getLyric(newS.mid)
        console.log('hahah')
      })
    },
    // 参数为playing的值
    playing(flag) {
      const audio = this.$refs.audio
      this.$nextTick(() => {
        flag ? audio.play() : audio.pause()
      })
    },
    currentTime(newTime) {
      this.precent = this.currentTime / this.playingSong.duration
    }
  },
  components: {
    Bar,
    scroll
  }
}
</script>

<style lang="stylus"  scoped>
@import '../../common/stylus/variable';
@import '../../common/stylus/mixin';

.player .normal-player.fullScreen {
  z-index: -1;
}

.player {
  .normal-player {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 150;
    background: $color-background;

    .background {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(20px);
    }

    .top {
      position: relative;
      margin-bottom: 25px;

      .back {
        position: absolute;
        top: 0;
        left: 6px;
        z-index: 50;

        .icon-back {
          display: block;
          padding: 9px;
          font-size: $font-size-large-x;
          color: $color-theme;
          transform: rotate(-90deg);
        }
      }

      .title {
        width: 70%;
        margin: 0 auto;
        line-height: 40px;
        text-align: center;
        no-wrap();
        font-size: $font-size-large;
        color: $color-text;
      }

      .subtitle {
        line-height: 20px;
        text-align: center;
        font-size: $font-size-medium;
        color: $color-text;
      }
    }

    .middle {
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;
      font-size: 0;

      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;

        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;

          .cd {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 10px solid rgba(255, 255, 255, 0.1);
            border-radius: 50%;

            &.play {
              animation: rotate 20s linear infinite;
            }

            &.pause {
              animation-play-state: paused;
            }

            .image {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
        }

        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;

          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: $font-size-medium;
            color: $color-text-l;
          }
        }
      }

      .middle-r {
        display: inline-block;
        vertical-align: top;
        width: 100%;
        height: 100%;
        overflow: hidden;

        .lyric-wrapper {
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;

          .text {
            line-height: 32px;
            color: $color-text-l;
            font-size: $font-size-medium;

            &.current {
              color: $color-text;
            }
          }
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;

      .dot-wrapper {
        text-align: center;
        font-size: 0;

        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;

          &.active {
            width: 20px;
            border-radius: 5px;
            background: $color-text-ll;
          }
        }
      }

      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 80%;
        margin: 0px auto;
        padding: 10px 0;

        .time {
          color: $color-text;
          font-size: $font-size-small;
          flex: 0 0 30px;
          line-height: 30px;
          width: 30px;

          &.time-l {
            text-align: left;
          }

          &.time-r {
            text-align: right;
          }
        }

        .progress-bar-wrapper {
          flex: 1;
        }
      }

      .operators {
        display: flex;
        align-items: center;

        .icon {
          flex: 1;
          color: $color-theme;

          &.disable {
            color: $color-theme-d;
          }

          i {
            font-size: 30px;
          }
        }

        .i-left {
          text-align: right;
        }

        .i-center {
          padding: 0 20px;
          text-align: center;

          i {
            font-size: 40px;
          }
        }

        .i-right {
          text-align: left;
        }

        .icon-favorite {
          color: $color-sub-theme;
        }
      }
    }

    &.normal-enter-active, &.normal-leave-active {
      transition: all 0.4s;

      .top, .bottom {
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
      }
    }

    &.normal-enter, &.normal-leave-to {
      opacity: 0;

      .top {
        transform: translate3d(0, -100px, 0);
      }

      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }

  .mini-player {
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 180;
    width: 100%;
    height: 60px;
    background: $color-highlight-background;

    &.mini-enter-active, &.mini-leave-active {
      transition: all 0.4s;
    }

    &.mini-enter, &.mini-leave-to {
      opacity: 0;
    }

    .icon {
      flex: 0 0 40px;
      width: 40px;
      padding: 0 10px 0 20px;

      img {
        border-radius: 50%;

        &.play {
          animation: rotate 10s linear infinite;
        }

        &.pause {
          animation-play-state: paused;
        }
      }
    }

    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      line-height: 20px;
      overflow: hidden;

      .name {
        margin-bottom: 2px;
        no-wrap();
        font-size: $font-size-medium;
        color: $color-text;
      }

      .desc {
        no-wrap();
        font-size: $font-size-small;
        color: $color-text-d;
      }
    }

    .control {
      flex: 0 0 30px;
      width: 30px;
      padding: 0 10px;

      .icon-play-mini, .icon-pause-mini, .icon-playlist {
        font-size: 30px;
        color: $color-theme-d;
      }

      .icon-mini {
        font-size: 32px;
        position: absolute;
        left: 0;
        top: 0;
      }
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
